package com.szwistar.common.comm;

import java.net.InetAddress;
import java.net.InetSocketAddress;

public class InetSocketAddressEx extends InetSocketAddress {
	private static final long serialVersionUID = -591368915802369249L;

	public InetSocketAddressEx(InetAddress addr, int port) {
		super(addr, port);
	}

	public InetSocketAddressEx(int port) {
		super(port);
	}

	public InetSocketAddressEx(String hostname, int port) {
		super(hostname, port);
	}

	public InetSocketAddressEx(InetSocketAddress another) {
		super(another.getHostString(), another.getPort());
	}

	@Override
	public String toString() {
		String addr = "*";
		if(getAddress() != null) {
			if(getAddress().isAnyLocalAddress()) {
				addr = "*";
			} else {
				addr = getAddress().getHostAddress();
			}
		} else {
			addr = getHostString();
		}
		return String.format("%s:%d", addr, getPort());
	}

	/**
	 * 解析字符串格式的地址
	 * @param str 地址格式形如："192.168.0.196:9488" / "*:9488"(当地址用做服务器监听地址时，IP地址可以用"*"，表示在所有本地IP地址上监听)
	 * @return
	 * @throws Exception
	 */
	public static InetSocketAddressEx fromString(String str) throws Exception {
		String[] parts = str.split(":");
		if(parts.length != 2 || parts[0].isEmpty()) {
			throw new Exception("非法的地址格式: " + str);
		}
		if("*".equals(parts[0]) || "0.0.0.0".equals(parts[0])) {
			return new InetSocketAddressEx(Integer.parseInt(parts[1]));
		}
		return new InetSocketAddressEx(parts[0], Integer.parseInt(parts[1]));
	}
}
